<template>
    <div class="vehicle-page">
        <div class="page-title">车辆管理</div>

        <!-- 查询区域 -->
        <div class="search-bar card">
            <div class="form-row">
                <label class="form-label">厂牌型号:</label>
                <input v-model.trim="query.brandModel" class="input" placeholder="请输入厂牌型号" />

                <label class="form-label">车牌号:</label>
                <input v-model.trim="query.plateNumber" class="input" placeholder="请输入车牌号" />

                <label class="form-label">司机姓名:</label>
                <input v-model.trim="query.driverName" class="input" placeholder="请输入司机姓名" />

                <label class="form-label">所属公司:</label>
                <input v-model.trim="query.company" class="input" placeholder="请输入所属公司" />

                <button class="btn primary" @click="handleSearch">查询</button>
                <button class="btn" @click="handleReset">重置</button>
            </div>
        </div>

        <!-- 操作 -->
        <div class="toolbar">
            <button class="btn primary" @click="handleCreate">新增</button>
            <button class="btn danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">删除</button>
        </div>

        <!-- 表格 -->
        <div class="card">
            <table class="table">
                <thead>
                    <tr>
                        <th class="col-checkbox">
                            <input type="checkbox" :checked="isAllChecked" @change="toggleAll($event)" />
                        </th>
                        <th>厂牌型号</th>
                        <th>车辆类型</th>
                        <th>车牌号</th>
                        <th>司机姓名</th>
                        <th>所属公司</th>
                        <th>车型（长*宽*高）</th>
                        <th>车辆颜色</th>
                        <th>购置日期</th>
                        <th>营运证号</th>
                        <th>保险到期时间</th>
                        <th>年检到期时间</th>
                        <th>保养公里设置</th>
                        <th class="col-actions">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="row in tableList" :key="row.id">
                        <td class="col-checkbox">
                            <input type="checkbox" :checked="selectedIds.includes(row.id)"
                                @change="toggleOne(row.id, $event)" />
                        </td>
                        <td>{{ row.brandModel }}</td>
                        <td>{{ row.vehicleType || '-' }}</td>
                        <td>{{ row.plateNumber }}</td>
                        <td>{{ row.driverName || '-' }}</td>
                        <td>{{ row.company || '-' }}</td>
                        <td>{{ row.size }}</td>
                        <td>{{ row.color }}</td>
                        <td>{{ row.purchaseDate }}</td>
                        <td>{{ row.operationCert }}</td>
                        <td>{{ row.insuranceExpire }}</td>
                        <td>{{ row.annualInspectExpire }}</td>
                        <td>{{ row.maintenanceKm }}</td>
                        <td class="col-actions">
                            <a href="javascript:void(0)" @click="handleEdit(row)">编辑</a>
                            <span class="divider">|</span>
                            <a href="javascript:void(0)" class="danger" @click="handleDelete(row)">删除</a>
                            <span class="divider">|</span>
                            <a href="javascript:void(0)" @click="handleView(row)">查看</a>
                        </td>
                    </tr>
                    <tr v-if="tableList.length === 0">
                        <td class="empty" colspan="13">暂无数据</td>
                    </tr>
                </tbody>
            </table>

            <!-- 分页 -->
            <div class="pagination">
                <div class="summary">共{{ totalPages }}页/{{ totalCount }}条数据</div>
                <div class="pager">
                    <button class="pager-btn" :disabled="page === 1" @click="goTo(page - 1)">‹</button>
                    <button v-for="p in pagesToShow" :key="p" class="pager-btn" :class="{ active: page === p }"
                        @click="goTo(p)">{{ p }}</button>
                    <button class="pager-btn" :disabled="page === totalPages || totalPages === 0"
                        @click="goTo(page + 1)">›</button>
                    <span class="goto">
                        跳至
                        <input class="goto-input" type="number" v-model.number="gotoPage" min="1"
                            :max="Math.max(totalPages, 1)" />
                        页
                        <button class="pager-btn" @click="confirmGoto">确定</button>
                    </span>
                </div>
            </div>
        </div>
    </div>
    <!-- 详情弹窗 -->
    <div v-if="showDetail" class="modal-mask">
        <div class="modal">
            <div class="modal-header">
                <div>车辆详情</div>
                <button class="modal-close" @click="closeDetail">×</button>
            </div>
            <div class="modal-body">
                <div v-if="detailLoading">加载中...</div>
                <div v-else-if="!detail">无数据</div>
                <div v-else>
                    <div class="detail-row"><span class="label">厂牌型号：</span><span>{{ detail.brandModel ||
                        detail.factoryModel || detail.brandandModel || detail.brandAndModel ||
                        detail.factoryAndModel || '-' }}</span></div>
                    <div class="detail-row"><span class="label">车牌号：</span><span>{{ detail.plateNumber ||
                        detail.licensePlateNumber || '-' }}</span></div>
                    <div class="detail-row"><span class="label">司机姓名：</span><span>{{ detail.driverName ||
                        detail.ownerName || detail.driver || detail.driver_name || detail.owner || '-' }}</span>
                    </div>
                    <div class="detail-row"><span class="label">所属公司：</span><span>{{ detail.company ||
                        detail.companyName || detail.affiliatedCompany || detail.affiliationCompany ||
                        detail.belongCompany || detail.unitName || detail.organization || detail.orgName || '-'
                            }}</span></div>
                    <div class="detail-row"><span class="label">车辆类型：</span><span>{{ detail.vehicleType || detail.type
                        || detail.vehicleCategory || '-' }}</span></div>
                    <div class="detail-row"><span class="label">车型尺寸：</span><span>{{ detail.size || detail.vehicleSize
                        || [detail.long, detail.width, detail.height].filter(Boolean).join('*') || '-' }}</span>
                    </div>
                    <div class="detail-row"><span class="label">车辆颜色：</span><span>{{ detail.color || detail.vehicleColor
                        || '-' }}</span></div>
                    <div class="detail-row"><span class="label">购置日期：</span><span>{{ detail.purchaseDate || '-'
                    }}</span></div>
                    <div class="detail-row"><span class="label">营运证号：</span><span>{{ detail.operationCert ||
                        detail.operationCertificateNumber || '-' }}</span></div>
                    <div class="detail-row"><span class="label">保险到期：</span><span>{{ detail.insuranceExpire ||
                        detail.insuranceExpiryDate || detail.insuranceExpirationDate || '-' }}</span></div>
                    <div class="detail-row"><span class="label">年检到期：</span><span>{{ detail.annualInspectExpire ||
                        detail.annualInspectionExpiryDate || detail.annualInspectionExpirationDate || '-' }}</span>
                    </div>
                    <div class="detail-row"><span class="label">保养公里：</span><span>{{ detail.maintenanceKm ||
                        detail.maintenanceMileageSetting || '-' }}</span></div>
                    <div class="detail-row"><span class="label">车辆照片：</span><span>
                            <template v-if="detail.vehiclePhotos">
                                <a v-if="detail.vehiclePhotos.startsWith('http')" :href="detail.vehiclePhotos"
                                    target="_blank"><img :src="detail.vehiclePhotos"
                                        style="max-height:60px;max-width:120px" /></a>
                                <img v-else :src="detail.vehiclePhotos" style="max-height:60px;max-width:120px" />
                            </template>
                            <span v-else>-</span>
                        </span></div>
                    <div class="detail-row"><span class="label">保险卡照片：</span><span>
                            <template v-if="detail.insuranceCardPhotos">
                                <a v-if="detail.insuranceCardPhotos.startsWith('http')"
                                    :href="detail.insuranceCardPhotos" target="_blank"><img
                                        :src="detail.insuranceCardPhotos" style="max-height:60px;max-width:120px" /></a>
                                <img v-else :src="detail.insuranceCardPhotos" style="max-height:60px;max-width:120px" />
                            </template>
                            <span v-else>-</span>
                        </span></div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn primary" @click="closeDetail">确定</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { read, write } from '@/assets/Axios/axiosHttple'

type VehicleRow = {
    id: number
    brandModel: string
    plateNumber: string
    driverName: string
    company: string
    vehicleType: string
    size: string
    color: string
    purchaseDate: string
    operationCert: string
    insuranceExpire: string
    annualInspectExpire: string
    maintenanceKm: string
}

// 查询参数
const query = reactive({
    brandModel: '',
    plateNumber: '',
    driverName: '',
    company: ''
})

// 数据
const tableList = ref<VehicleRow[]>([])
const totalCount = ref(0)

// 选择
const selectedIds = ref<number[]>([])
const isAllChecked = computed(() => tableList.value.length > 0 && tableList.value.every(r => selectedIds.value.includes(r.id)))

// 分页
const page = ref(1)
const pageSize = ref(10)
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))
const pagesToShow = computed(() => {
    const total = totalPages.value
    if (total === 0) return [] as number[]
    const max = 7
    const result: number[] = []
    let start = Math.max(1, page.value - 3)
    let end = Math.min(total, start + max - 1)
    if (end - start + 1 < max) start = Math.max(1, end - max + 1)
    for (let i = start; i <= end; i++) result.push(i)
    return result
})
const gotoPage = ref<number | ''>('')

function goTo(p: number) { if (p < 1 || p > totalPages.value) return; page.value = p; fetchList() }
function confirmGoto() { if (typeof gotoPage.value === 'number') goTo(gotoPage.value) }

function handleSearch() { page.value = 1; fetchList() }
function handleReset() { query.brandModel = ''; query.plateNumber = ''; query.driverName = ''; query.company = ''; page.value = 1; fetchList() }

function toggleAll(ev: Event) {
    const checked = (ev.target as HTMLInputElement).checked
    if (checked) selectedIds.value = Array.from(new Set([...selectedIds.value, ...tableList.value.map(r => r.id)]))
    else {
        const ids = new Set(tableList.value.map(r => r.id))
        selectedIds.value = selectedIds.value.filter(id => !ids.has(id))
    }
}
function toggleOne(id: number, ev: Event) {
    const checked = (ev.target as HTMLInputElement).checked
    if (checked) { if (!selectedIds.value.includes(id)) selectedIds.value.push(id) }
    else selectedIds.value = selectedIds.value.filter(x => x !== id)
}

function handleCreate() { window.location.href = '/AddVehicleManagement' }
function handleEdit(row: VehicleRow) { window.location.href = `/UpdateVehicleManagement?id=${encodeURIComponent(String(row.id))}` }
async function handleDelete(row: VehicleRow) {
    if (!confirm(`确认删除【${row.plateNumber}】吗？`)) return
    try {
        const res = await write.post('baseinfowrite/api/VehicleManagement/Delete', { id: row.id, deletedBy: localStorage.getItem('username') || 'system' })
        const json = res?.data
        if (res?.status === 200 && (json?.code === 200 || json?.data === true)) {
            tableList.value = tableList.value.filter(v => v.id !== row.id)
            totalCount.value = Math.max(0, totalCount.value - 1)
            selectedIds.value = selectedIds.value.filter(id => id !== row.id)
        } else {
            console.error('删除失败', json)
        }
    } catch (e) {
        console.error('删除接口异常', e)
    }
}
async function handleBatchDelete() {
    if (selectedIds.value.length === 0) return
    if (!confirm(`确认批量删除选中的 ${selectedIds.value.length} 条记录吗？`)) return
    try {
        const payload = { ids: selectedIds.value, deletedBy: localStorage.getItem('username') || 'system' }
        const res = await write.post('baseinfowrite/api/VehicleManagement/BatchDeletete', payload)
        const json = res?.data
        if (res?.status === 200 && json?.code === 200) {
            const set = new Set(selectedIds.value)
            tableList.value = tableList.value.filter(v => !set.has(v.id))
            totalCount.value = Math.max(0, totalCount.value - set.size)
            selectedIds.value = []
        } else {
            console.error('批量删除失败', json)
        }
    } catch (e) {
        console.error('批量删除接口异常', e)
    }
}
function handleView(row: VehicleRow) { openDetail(row.id) }

// 详情弹窗
const showDetail = ref(false)
const detailLoading = ref(false)
const detail = ref<any>(null)

async function openDetail(id: number) {
    showDetail.value = true
    detailLoading.value = true
    detail.value = null
    try {
        const res1 = await read.get(`baseinforead/api/VehicleManagement/GetVehicleById/${encodeURIComponent(String(id))}`)
        const d = res1?.data?.data
        if (d) detail.value = d
        else detail.value = null
    } catch (e) {
        console.error('获取车辆详情失败', e)
        detail.value = null
    } finally {
        detailLoading.value = false
    }
}

function closeDetail() { showDetail.value = false }

async function fetchList() {
    try {
        const params = new URLSearchParams()
        const add = (k: string, v: string) => { if (v) params.append(k, v) }
        add('PageIndex', String(page.value))
        add('PageSize', String(pageSize.value))
        // 厂牌型号别名
        const bm = (query.brandModel || '').trim()
        add('brandModel', bm); add('factoryModel', bm); add('brandandModel', bm); add('brandAndModel', bm)
        // 车牌号别名
        const pn = (query.plateNumber || '').trim()
        add('plateNumber', pn); add('licensePlateNumber', pn)
        // 司机姓名别名
        const dn = (query.driverName || '').trim()
        add('driverName', dn); add('ownerName', dn); add('driver', dn); add('driver_name', dn)
        // 所属公司别名
        const cp = (query.company || '').trim()
        add('company', cp); add('companyName', cp); add('affiliatedCompany', cp); add('affiliationCompany', cp); add('belongCompany', cp); add('unitName', cp)
        // 防缓存
        add('t', String(Date.now()))

        const res = await read.get('baseinforead/api/VehicleManagement/GetVehicleList', { params })
        const payload = res?.data?.data ?? { totalCount: 0, data: [] }
        const list = Array.isArray(payload?.data) ? payload.data : []
        tableList.value = list.map((it: any, idx: number) => {
            const size = it.size || it.vehicleSize || it.vehicleType || [it.long, it.width, it.height].filter(Boolean).join('*') || ''
            return {
                id: it.id ?? idx + 1,
                brandModel: it.brandModel ?? it.factoryModel ?? it.brandandModel ?? '',
                plateNumber: it.plateNumber ?? it.licensePlateNumber ?? '',
                driverName: it.driverName ?? it.ownerName ?? it.driver ?? it.driver_name ?? '',
                company: it.company ?? it.companyName ?? it.affiliatedCompany ?? it.affiliationCompany ?? it.belongCompany ?? it.unitName ?? '',
                vehicleType: it.vehicleType ?? it.type ?? it.vehicleCategory ?? '',
                size,
                color: it.color ?? it.vehicleColor ?? '',
                purchaseDate: it.purchaseDate ?? '',
                operationCert: it.operationCert ?? it.operationCertificateNumber ?? '',
                insuranceExpire: it.insuranceExpire ?? it.insuranceExpiryDate ?? it.insuranceExpirationDate ?? '',
                annualInspectExpire: it.annualInspectExpire ?? it.annualInspectionExpiryDate ?? it.annualInspectionExpirationDate ?? '',
                maintenanceKm: it.maintenanceKm ?? it.maintenanceMileageSetting ?? ''
            }
        })
        totalCount.value = Number(payload.totalCount ?? tableList.value.length)
    } catch (e) {
        console.error('获取车辆列表失败', e)
        tableList.value = []
        totalCount.value = 0
    }
}

fetchList()
</script>

<style scoped>
.vehicle-page {
    padding: 16px 20px;
    color: #333;
    font-size: 14px;
}

.page-title {
    font-size: 18px;
    margin-bottom: 12px;
}

.card {
    background: #fff;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
}

.search-bar {
    padding: 16px;
    margin-bottom: 12px;
}

.form-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px 12px;
}

.form-label {
    color: #666;
}

.input {
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
    min-width: 180px;
}

.btn {
    height: 32px;
    padding: 0 14px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.btn.primary {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.btn.danger {
    color: #f56c6c;
    border-color: #f56c6c;
}

.toolbar {
    margin: 8px 0 12px 0;
    display: flex;
    gap: 8px;
}

.table {
    width: 100%;
    border-collapse: collapse;
}

.table thead th {
    text-align: left;
    background: #f7f8fa;
    border-bottom: 1px solid #e5e6eb;
    padding: 10px 12px;
    color: #666;
    font-weight: 400;
}

.table tbody td {
    border-bottom: 1px solid #f0f0f0;
    padding: 10px 12px;
}

.col-checkbox {
    width: 36px;
}

.col-actions {
    width: 180px;
    white-space: nowrap;
}

.divider {
    color: #d0d0d0;
    margin: 0 6px;
}

.danger {
    color: #f56c6c;
}

.empty {
    text-align: center;
    color: #909399;
}

.pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
}

.summary {
    color: #909399;
}

.pager {
    display: flex;
    align-items: center;
    gap: 4px;
}

.pager-btn {
    min-width: 28px;
    height: 28px;
    padding: 0 8px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 3px;
    cursor: pointer;
}

.pager-btn.active {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.goto {
    margin-left: 8px;
    color: #606266;
}

.goto-input {
    width: 56px;
    height: 28px;
    margin: 0 6px;
    padding: 0 6px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
}

/* 弹窗样式 */
.modal-mask {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .35);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
}

.modal {
    width: 560px;
    background: #fff;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, .2);
}

.modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 14px;
    background: #f7f8fa;
    border-bottom: 1px solid #ebeef5;
}

.modal-close {
    border: none;
    background: transparent;
    font-size: 18px;
    cursor: pointer;
}

.modal-body {
    padding: 12px 14px;
}

.detail-row {
    margin-bottom: 8px;
    display: flex;
}

.detail-row .label {
    width: 100px;
    color: #666;
}

.modal-footer {
    padding: 10px 14px;
    text-align: right;
    border-top: 1px solid #ebeef5;
}
</style>
